//
//  TW_HeroSprite.m
//  Tower
//
//  Created by Jonear on 14-5-11.
//  Copyright (c) 2014年 Jonear. All rights reserved.
//

#import "TW_HeroSprite.h"

#define MoveDistance 18
@implementation TW_HeroSprite
{
    SKTextureAtlas *_atlas;
}

- (instancetype)initWithPosition:(CGPoint)position
{
    _atlas = [SKTextureAtlas atlasNamed:@"hero"];
    self = (TW_HeroSprite*)[TW_HeroSprite spriteNodeWithTexture:[_atlas textureNamed:@"hero"]];
    if (self) {
        self.position = position;
    }
    return self;
}

- (void)heroMoveTo:(enumHeroMove)move
{
    if (![self isCanMove:move]) {
        return;
    }
    NSMutableArray *textures = [[NSMutableArray alloc] init];
    _atlas = [SKTextureAtlas atlasNamed:@"hero"];
    NSString *textureNameString;
    SKAction *moveAction;
    if (move == kMoveDown) {
        textureNameString = @"hero_down";
        moveAction = [SKAction moveToY:self.position.y-MoveDistance duration:0.1];
    } else if (move == kMoveLeft) {
        textureNameString = @"hero_left";
        moveAction = [SKAction moveToX:self.position.x-MoveDistance duration:0.1];
    } else if (move == kMoveUp) {
        textureNameString = @"hero_up";
        moveAction = [SKAction moveToY:self.position.y+MoveDistance duration:0.1];
    } else if (move == kMoveRight) {
        textureNameString = @"hero_right";
        moveAction = [SKAction moveToX:self.position.x+MoveDistance duration:0.1];
    }
    _currentDirection = move;
    
    for (int i=4; i>0; i--) {
        SKTexture *texture = [_atlas textureNamed:[NSString stringWithFormat:@"%@%d", textureNameString, i]];
        [textures addObject:texture];
    }
    
    SKAction *imageAction = [SKAction animateWithTextures:textures timePerFrame:0.1];
    
    [self runAction:[SKAction group:@[imageAction, moveAction]]];
}

- (BOOL)isCanMove:(enumHeroMove)direction
{
    if (direction == kMoveDown && _currectPoint.y==7) {
        return NO;
    } else if (direction == kMoveLeft && _currectPoint.x==0) {
        return NO;
    } else if (direction == kMoveUp  && _currectPoint.y==0) {
        return NO;
    } else if (direction == kMoveRight && _currectPoint.x==7) {
        return NO;
    }
    
    
    if (direction == kMoveDown) {
        _currectPoint.y ++;
    } else if (direction == kMoveLeft) {
        _currectPoint.x --;
    } else if (direction == kMoveUp) {
        _currectPoint.y --;
    } else if (direction == kMoveRight) {
        _currectPoint.x ++;
    }
    
    NSLog(@"x=%f, y=%f", _currectPoint.x, _currectPoint.y);
    return YES;
}

@end
